//
//  SXRequestManager.m
//  ShiXun
//
//  Created by lanou on 15/10/24.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXRequestManager.h"

@implementation SXRequestManager

+ (void)requestWithType:(RequestType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error
{
    SXRequestManager *manager = [[SXRequestManager alloc] init];
    [manager requestWithType:type urlString:urlString parDic:parDic finish:finish error:error];
}

- (void)requestWithType:(RequestType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 判断请求方式，如果是POST需要设置参数和请求方式
    if (type == POST)
    {
        [request setHTTPMethod:@"POST"];
        if (parDic.count > 0){
            NSData *data = [self parDicToDataWithDic:parDic];
            [request setHTTPBody:data];
        }
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            finish(data);
        }else{
            error(connectionError);
        }
    }];
}

// 将POST请求的参数字典转换成NSData
- (NSData *)parDicToDataWithDic:(NSDictionary *)dic
{
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@", key, dic[key]];
        [array addObject:str];
    }
    NSString *parString = [array componentsJoinedByString:@"&"];
    return [parString dataUsingEncoding:NSUTF8StringEncoding];
}


@end
